package com.xing.export.ui;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;

import com.xing.export.R;
import com.xing.export.adapter.ContactsAdapter;
import com.xing.export.bean.PhoneBean;
import com.xing.export.util.ExportUtil;
import com.xing.export.util.StringUtils;

public class ContactsActivity extends BaseActivity {

	private static String TAG = "ContactsActivity";
	public final static  String EXPORT_TXT = "txt";
	public final static  String EXPORT_EXCEL = "excel";
	public final static  String EXPORT_PDF = "pdf";
	
	private String type =null;
	
    private List<PhoneBean> data = new ArrayList<PhoneBean>();
    private ListView mListView = null;
    private ContactsAdapter contactsAdapter = null;
    private Button save_btn;
    private ImageView back_img;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	   super.onCreate(savedInstanceState);
           setContentView(R.layout.contact_detail);
			mListView = (ListView) findViewById(R.id.contact_detail_list);
			save_btn = (Button) findViewById(R.id.contact_second_button);
			back_img = (ImageView) findViewById(R.id.contact_detail_back);
			
			//获取数据
			type = getIntent().getStringExtra(MainActivity.EXPORT_TYPE);
			
			/**得到手机通讯录联系人信息**/
			List<PhoneBean> list = ExportUtil.findPhoneContacts(this, getResources());
			data.addAll(list);
			
			contactsAdapter = new ContactsAdapter(this, data, R.layout.phonelist);
			mListView.setAdapter(contactsAdapter);
			
			save_btn.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if(EXPORT_TXT.equals(type)){
						saveTxt();
					}else if(EXPORT_EXCEL.equals(type)){
						writeExcel();
					}
					
				}
			});
			back_img.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					ContactsActivity.this.finish();
					
				}
			});
    }
    public void writeExcel() {
        try{
        	//判断是否挂载了SD卡
    		String storageState = Environment.getExternalStorageState();		
    		String savePath = null;
    		if(storageState.equals(Environment.MEDIA_MOUNTED)){
    			savePath = Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator+ "export";
    			File file = new File(savePath);
    			if(!file.exists()){
    				file.mkdirs();
    			}
    		}
    		
    		if(StringUtils.isBlank(savePath)){
    			File dirConf = this.getDir("export", Context.MODE_PRIVATE);
    			savePath =dirConf.getPath();
    		}
    		
    		savePath +=File.separator+ "address.xls";//.xls
    		Log.e(TAG, "savePath="+savePath); 
            //创建一个可写入的工作薄(Workbook)对象
    		WritableWorkbook  wwb = Workbook.createWorkbook(new File(savePath));
            if (wwb != null) {
                // 第一个参数是工作表的名称，第二个是工作表在工作薄中的位置
                WritableSheet ws = wwb.createSheet("address", 0);
                // 在指定单元格插入数据
                List<PhoneBean> beans = ExportUtil.findPhoneContacts(this,getResources());
            	Log.e(TAG, "beans="+beans); 
                if(beans!=null && beans.size()>0){
                	PhoneBean phoneBean = null;
                	 Label bll =null;
                	for(int i=0;i<beans.size();i++){
                		 phoneBean = beans.get(i);
                		 bll = new Label(0,i , phoneBean.getContactName());
                		 ws.addCell(bll);
                		 bll = new Label(1, i, phoneBean.getPhoneNumber());
                		 ws.addCell(bll);
                	}
                }
                // 从内存中写入文件中
                wwb.write();
                wwb.close();
                
              //显示一下保存路径
                ExportUtil.showMessage(this, savePath);
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriteException e) {
			e.printStackTrace();
		}
    }
    
    public void saveTxt(){
    	//判断是否挂载了SD卡
		String storageState = Environment.getExternalStorageState();		
		String savePath = null;
		if(storageState.equals(Environment.MEDIA_MOUNTED)){
			savePath = Environment.getExternalStorageDirectory().getAbsolutePath() +File.separator+ "export";
			File file = new File(savePath);
			if(!file.exists()){
				file.mkdirs();
			}
		}
		
		if(StringUtils.isBlank(savePath)){
			File dirConf = this.getDir("export", Context.MODE_PRIVATE);
			savePath =dirConf.getPath();
		}
		
		savePath +=File.separator+ "address.txt";
		
		FileOutputStream output=null;
        try {
        	output = new FileOutputStream(savePath);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
        PrintStream out=new PrintStream(output);
        out.print(ExportUtil.ListToString(ExportUtil.findPhoneContacts(this,getResources())));
        out.close();
        //显示一下保存路径
        ExportUtil.showMessage(this, savePath);
    }
 
}